<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="40">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作业名称" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交开始时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交结束时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.etime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交缓冲时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.btime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作业地址" align="center">
        <template slot-scope="{row}">
          <span><a :href="returnImageUrl(row.url)" target="_blank" rel="noopener">{{ returnImageUrl(row.url) }}</a></span>
        </template>
      </el-table-column>
      <el-table-column label="是否确认分数" align="center">
        <template slot-scope="{row}">
          <span>{{ isConfirmScoreOption[row.score_confirm] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分数确认签字" align="center">
        <template slot-scope="{row}">
          <span>{{ row.score_confirm_sign_url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="success" size="mini" @click="jumpHomeworkTeacher(row)">
            作业成绩管理
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="作业名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="提交开始时间" prop="stime">
          <div class="block">
            <el-date-picker
              v-model="temp.stime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="提交开始时间"
            />
          </div>
        </el-form-item>
        <el-form-item label="提交结束时间" prop="etime">
          <div class="block">
            <el-date-picker
              v-model="temp.etime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="提交结束时间"
            />
          </div>
        </el-form-item>
        <el-form-item label="提交缓冲时间" prop="btime">
          <div class="block">
            <el-date-picker
              v-model="temp.btime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="提交缓冲时间"
            />
          </div>
        </el-form-item>
        <el-form-item label="作业地址" prop="url">
          <PdfUpload :upload-name="uploadName" :upload-url="temp.url" @getReturnUrl="setReturnUrl" />
        </el-form-item>
        <el-form-item label="是否确认分数" prop="score_confirm">
          <el-select v-model="temp.score_confirm" class="filter-item">
            <el-option v-for="(value,key) in isConfirmScoreOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { homeworkPage, homeworkCreate, homeworkDelete, homeworkUpdate } from '@/api/homework'
import waves from '@/directive/waves' // waves directive
import { notifySuccess, formatJson, my_confirm, listQueryFilter, getFileUrl } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import PdfUpload from '@/components/Upload/PdfUpload'

export default {
  name: 'ClassPage',
  components: { Pagination, PdfUpload },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        course_timetable_id: this.$route.query.id
      },
      isConfirmScoreOption: {
        0: '否',
        1: '是'
      },
      temp: {
        id: undefined,
        name: '',
        stime: '',
        etime: '',
        btime: '',
        url: '',
        score_confirm: '',
        score_confirm_sign_url: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        name: [{ required: true, message: '作业名称必填', trigger: 'change' }],
        stime: [{ required: true, message: '提交开始时间必填', trigger: 'change' }],
        etime: [{ required: true, message: '提交结束时间必填', trigger: 'change' }],
        url: [{ required: true, message: '作业地址必填', trigger: 'change' }],
        score_confirm: [{ required: true, message: '是否确认分数', trigger: 'change' }]
      },
      uploadName: 'UpLoadPdf',
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      homeworkPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        course_timetable_id: this.$route.query.id,
        name: '',
        stime: '',
        etime: '',
        btime: '',
        url: '',
        score_confirm: '0',
        score_confirm_sign_url: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.btime === null) {
            delete this.temp.btime
          }
          homeworkCreate(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.name = row.name
      this.temp.stime = row.stime
      this.temp.etime = row.etime
      this.temp.btime = row.btime
      this.temp.url = row.url
      this.temp.score_confirm = row.score_confirm
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          if (tempData.btime === null) {
            delete tempData.btime
          }
          homeworkUpdate(tempData).then(response => {
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        homeworkDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    jumpHomeworkTeacher(row) {
      this.$router.push({
        path: '/homework/teacher',
        query: {
          homeworkId: row.id
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['年', '季度', '学期', '班级名称', '班级简称', '小到大', '是否app显示', '是否删除', '班级类型']
        const filterVal = ['year', 'quarter', 'semester', 'name', 'short_name', 'sort', 'is_show', 'is_del', 'type']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '班级表'
        })
        this.downloadLoading = false
      })
    },
    returnImageUrl(url) {
      return getFileUrl(url)
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    setReturnUrl: function(data) {
      this.temp.url = data
      notifySuccess(this, 'pdf文件上传成功,请点击确定修改')
    }
  }
}
</script>

